<template>
  <div class="task-list-container">
    <n-layout has-sider>
      <!-- 侧边栏 - 任务分组 -->
      <n-layout-sider
        bordered
        collapse-mode="width"
        :collapsed-width="64"
        :width="240"
        show-trigger
        @collapse="collapsed = true"
        @expand="collapsed = false"
      >
        <div class="sidebar-header">
          <h2 v-if="!collapsed">任务分组</h2>
          <n-button v-else text @click="showCreateGroupModal = true">
            <n-icon><Add /></n-icon>
          </n-button>
        </div>
        
        <div class="group-actions" v-if="!collapsed">
          <n-button block secondary @click="showCreateGroupModal = true" :loading="loading">
            <template #icon>
              <n-icon><Add /></n-icon>
            </template>
            新建分组
          </n-button>
        </div>
        
        <n-menu
          v-model:value="currentGroupId"
          :options="menuOptions"
          @update:value="handleGroupChange"
        />
      </n-layout-sider>
      
      <!-- 主内容区 -->
      <n-layout>
        <n-layout-header bordered>
          <div class="header-content">
            <h1>{{ currentGroupName }}</h1>
            <div class="header-actions">
              <n-button secondary @click="goToMyDay">
                我的一天
              </n-button>
              <n-button type="primary" @click="showCreateTaskModal = true">
                <template #icon>
                  <n-icon><Add /></n-icon>
                </template>
                新建任务
              </n-button>
              <n-button @click="handleLogout">
                退出
              </n-button>
            </div>
          </div>
        </n-layout-header>
        
        <n-layout-content class="content">
          <!-- 任务过滤器 -->
          <div class="filter-bar">
            <n-space>
              <n-select
                v-model:value="filterStatus"
                :options="statusOptions"
                placeholder="状态筛选"
                clearable
                @update:value="handleFilterChange"
              />
              <n-checkbox v-model:checked="filterImportant" @update:checked="handleFilterChange">
                重要任务
              </n-checkbox>
            </n-space>
          </div>
          
          <!-- 任务列表 -->
          <div class="task-list">
            <n-list>
              <n-list-item v-for="task in tasks" :key="task.task_id">
                <n-thing>
                  <template #header>
                    <div class="task-header">
                      <n-checkbox
                        :checked="task.status === 2"
                        @update:checked="(val: boolean) => toggleTaskStatus(task, val)"
                      />
                      <span :class="{ 'task-completed': task.status === 2 }">{{ task.title }}</span>
                      <n-tag v-if="task.is_important" type="error" size="small">重要</n-tag>
                      <n-tag v-if="task.is_my_day" type="warning" size="small">我的一天</n-tag>
                    </div>
                  </template>
                  <template #description>
                    <div class="task-description">
                      {{ task.description }}
                    </div>
                    <div class="task-meta">
                      <span>{{ formatDate(task.created_at) }}</span>
                      <span v-if="task.due_date">截止: {{ formatDate(task.due_date) }}</span>
                    </div>
                  </template>
                  <template #header-extra>
                    <n-button text @click="goToTaskDetail(task.task_id)">
                      <n-icon><Create /></n-icon>
                    </n-button>
                  </template>
                </n-thing>
              </n-list-item>
            </n-list>
          </div>
        </n-layout-content>
      </n-layout>
    </n-layout>
    
    <!-- 创建分组模态框 -->
    <n-modal v-model:show="showCreateGroupModal" preset="dialog" title="新建分组">
      <n-form
        ref="groupFormRef"
        :model="groupFormValue"
        :rules="groupRules"
      >
        <n-form-item label="分组名称" path="name">
          <n-input v-model:value="groupFormValue.name" placeholder="请输入分组名称" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-button @click="showCreateGroupModal = false">取消</n-button>
        <n-button type="primary" @click="handleCreateGroup">确定</n-button>
      </template>
    </n-modal>
    
    <!-- 创建任务模态框 -->
    <n-modal v-model:show="showCreateTaskModal" preset="dialog" title="新建任务">
      <n-form
        ref="taskFormRef"
        :model="taskFormValue"
        :rules="taskRules"
      >
        <n-form-item label="任务标题" path="title">
          <n-input v-model:value="taskFormValue.title" placeholder="请输入任务标题" />
        </n-form-item>
        <n-form-item label="任务描述" path="description">
          <n-input
            v-model:value="taskFormValue.description"
            type="textarea"
            placeholder="请输入任务描述"
          />
        </n-form-item>
        <n-form-item label="所属分组" path="group_id">
          <n-select
            v-model:value="taskFormValue.group_id"
            :options="groupSelectOptions"
            placeholder="请选择分组"
          />
        </n-form-item>
        <n-form-item label="截止日期" path="due_date">
          <n-date-picker
            v-model:value="taskFormValue.due_date"
            type="date"
            placeholder="请选择截止日期"
          />
        </n-form-item>
        <n-form-item label="重要性">
          <n-checkbox v-model:checked="taskFormValue.is_important">
            标记为重要
          </n-checkbox>
        </n-form-item>
        <n-form-item label="我的一天">
          <n-checkbox v-model:checked="taskFormValue.is_my_day">
            添加到我的一天
          </n-checkbox>
        </n-form-item>
      </n-form>
      <template #action>
        <n-button @click="showCreateTaskModal = false">取消</n-button>
        <n-button type="primary" @click="handleCreateTask" :loading="loading">确定</n-button>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import type { FormInst, FormRules } from 'naive-ui'
import { Add, Create } from '@vicons/ionicons5'

// 导入所有使用的Naive UI组件
import {
  NLayout,
  NLayoutSider,
  NLayoutHeader,
  NLayoutContent,
  NButton,
  NMenu,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NCheckbox,
  NDatePicker,
  NSpace,
  NTag,
  NThing,
  NList,
  NListItem,
  NModal,
  NIcon
} from 'naive-ui'

import { useGroupStore } from '../../stores/groupStore'
import { useTaskStore } from '../../stores/taskStore'
import { useUserStore } from '../../stores/userStore'
import type { Task } from '../../types/task'
import type { TaskGroup } from '../../types/group'

const router = useRouter()
const message = useMessage()
const groupStore = useGroupStore()
const taskStore = useTaskStore()
const userStore = useUserStore()

// 状态
const collapsed = ref(false)
const showCreateGroupModal = ref(false)
const showCreateTaskModal = ref(false)
const currentGroupId = ref<number | string | null>(null)
const loading = ref(false)

// 表单引用
const groupFormRef = ref<FormInst | null>(null)
const taskFormRef = ref<FormInst | null>(null)

// 过滤器
const filterStatus = ref<number | null>(null)
const filterImportant = ref<boolean>(false)

// 表单数据
const groupFormValue = ref({
  name: ''
})

const taskFormValue = ref({
  title: '',
  description: '',
  group_id: null as number | null,
  due_date: null as number | null,
  is_important: false,
  is_my_day: false
})

// 当组件挂载后，设置默认分组
onMounted(() => {
  // 如果当前有选中的分组，设置为默认分组
  if (currentGroupId.value !== null && currentGroupId.value !== 'all') {
    taskFormValue.value.group_id = typeof currentGroupId.value === 'string' ? 
                                 Number(currentGroupId.value) : 
                                 currentGroupId.value;
  } else {
    // 否则使用第一个可用的分组
    const groups = groupStore.getAllGroups;
    if (groups.length > 0 && groups[0]) {
      taskFormValue.value.group_id = groups[0].group_id;
    }
  }
})

// 表单规则
const groupRules: FormRules = {
  name: {
    required: true,
    message: '请输入分组名称',
    trigger: 'blur'
  }
}

const taskRules: FormRules = {
  title: {
    required: true,
    message: '请输入任务标题',
    trigger: 'blur'
  },
  group_id: {
    required: true,
    validator: (_rule, value) => {
      if (value === null || value === undefined) {
        return new Error('请选择所属分组');
      }
      // 检查值是否为有效数字
      if (typeof value !== 'number' || isNaN(value) || value <= 0) {
        return new Error('请选择有效的所属分组');
      }
      return true;
    },
    trigger: 'blur'
  }
}

// 计算属性
const menuOptions = computed(() => {
  const groups = groupStore.getAllGroups
  console.log('All groups for menu:', groups)
  if (!Array.isArray(groups)) {
    console.log('Groups is not an array:', groups)
    return []
  }
  
  // 添加"全部"选项作为第一个选项
  const allOption = {
    label: `全部任务`,
    key: 'all',
    icon: () => null
  }
  
  const groupOptions = groups.map((group: TaskGroup) => ({
    label: `${group.name} (${group.task_count || 0})`,
    key: group.group_id,
    icon: () => null
  }))
  
  // 将"全部"选项放在最前面
  return [allOption, ...groupOptions]
})

const currentGroupName = computed(() => {
  // 检查当前选择的是否是"全部"选项
  const isAllSelected = currentGroupId.value === null || currentGroupId.value === 'all'
  
  // 如果当前选择的是"全部"或没有选择分组，显示"全部任务"
  if (isAllSelected || !currentGroupId.value) {
    return '全部任务'
  }
  
  // 否则显示选中的分组名称（确保传入的是数字类型）
  const groupId = typeof currentGroupId.value === 'string' ? 
                 (currentGroupId.value === 'all' ? null : Number(currentGroupId.value)) : 
                 currentGroupId.value
  
  if (groupId === null) {
    return '全部任务'
  }
  
  const group = groupStore.getGroupById(groupId)
  return group ? group.name : '所有任务'
})

const groupSelectOptions = computed(() => {
  const groups = groupStore.getAllGroups
  console.log('All groups for select:', groups)
  if (!Array.isArray(groups)) {
    console.log('Groups is not an array:', groups)
    return []
  }
  return groups.map((group: TaskGroup) => ({
    label: group.name,
    value: group.group_id
  }))
})

const tasks = computed(() => {
  const allTasks = taskStore.getAllTasks
  console.log('All tasks:', allTasks)
  if (!Array.isArray(allTasks)) {
    console.log('Tasks is not an array:', allTasks)
    return []
  }
  return allTasks
})

const statusOptions = [
  { label: '新任务', value: 0 },
  { label: '进行中', value: 1 },
  { label: '已完成', value: 2 }
]

// 方法
const handleGroupChange = (key: string | number) => {
  currentGroupId.value = key === 'all' ? null : Number(key)
  // 如果选择的是"全部"，则不设置分组过滤
  if (key === 'all') {
    taskStore.setFilter({ groupId: null })
  } else {
    taskStore.setFilter({ groupId: Number(key) })
  }
  taskStore.fetchTasks()
}

const handleFilterChange = () => {
  taskStore.setFilter({
    status: filterStatus.value,
    isImportant: filterImportant.value
  })
  taskStore.fetchTasks()
}

const toggleTaskStatus = (task: Task, checked: boolean) => {
  const newStatus = checked ? 2 : 0
  taskStore.updateTask(task.task_id, { status: newStatus })
  
  // 如果任务是"我的一天"任务，也需要更新"我的一天"任务列表
  if (task.is_my_day) {
    taskStore.fetchMyDayTasks()
  }
}

const goToMyDay = () => {
  router.push('/tasks/my-day')
}

const goToTaskDetail = (taskId: number) => {
  router.push(`/tasks/${taskId}`)
}

const handleCreateGroup = () => {
  groupFormRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        loading.value = true
        const result = await groupStore.createGroup(groupFormValue.value.name)
        if (result.success) {
          message.success('分组创建成功')
          showCreateGroupModal.value = false
          groupFormValue.value.name = ''
        } else {
          message.error(result.message || '分组创建失败')
        }
      } catch (error) {
        message.error('分组创建过程中发生错误')
      } finally {
        loading.value = false
      }
    } else {
      message.error('请检查输入信息')
    }
  })
}

const handleCreateTask = () => {
  console.log('Task form value before validation:', taskFormValue.value)
  taskFormRef.value?.validate(async (errors) => {
    console.log('Validation errors:', errors)
    if (!errors) {
      try {
        loading.value = true
        // 确保group_id有有效值
        if (taskFormValue.value.group_id === null) {
          // 如果表单中没有选择分组，使用当前选中的分组
          if (currentGroupId.value !== null && currentGroupId.value !== 'all') {
            taskFormValue.value.group_id = typeof currentGroupId.value === 'string' ? 
                                          Number(currentGroupId.value) : 
                                          currentGroupId.value;
          } else {
            // 如果仍然没有分组，使用第一个可用的分组
            const groups = groupStore.getAllGroups;
            if (groups.length > 0 && groups[0]) {
              taskFormValue.value.group_id = groups[0].group_id;
            }
          }
        }
        
        console.log('Task form value before submission:', taskFormValue.value)
        
        // 处理日期格式
        const taskData = {
          ...taskFormValue.value,
          due_date: taskFormValue.value.due_date 
            ? new Date(taskFormValue.value.due_date).toISOString().split('T')[0] 
            : undefined
        }
        
        const result = await taskStore.createTask(taskData)
        console.log('Task creation result:', result)
        if (result.success) {
          message.success('任务创建成功')
          showCreateTaskModal.value = false
          
          // 重新获取任务列表以确保数据一致性
          await taskStore.fetchTasks()
          
          // 重置表单
          taskFormValue.value = {
            title: '',
            description: '',
            group_id: currentGroupId.value === 'all' || currentGroupId.value === null ? 
                      null : 
                      (typeof currentGroupId.value === 'string' ? Number(currentGroupId.value) : currentGroupId.value),
            due_date: null,
            is_important: false,
            is_my_day: false
          }
        } else {
          message.error(result.message || '任务创建失败')
        }
      } catch (error) {
        console.error('Error creating task:', error)
        message.error('任务创建过程中发生错误')
      } finally {
        loading.value = false
      }
    } else {
      message.error('请检查输入信息')
    }
  })
}

const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 监听分组变化，更新当前分组的任务
watch(
  () => groupStore.getAllGroups,
  (newGroups) => {
    console.log('Groups changed:', newGroups)
    if (newGroups.length > 0 && !currentGroupId.value) {
      const firstGroup = newGroups[0];
      if (firstGroup) {
        currentGroupId.value = firstGroup.group_id;
        taskFormValue.value.group_id = firstGroup.group_id;
        taskStore.setFilter({ groupId: firstGroup.group_id });
        taskStore.fetchTasks();
      }
    }
  },
  { immediate: true }
)

// 生命周期
onMounted(async () => {
  try {
    console.log('TaskList mounted, fetching data...')
    // 并行获取分组和任务数据
    await Promise.all([
      groupStore.fetchGroups(),
      taskStore.fetchTasks()
    ])
    
    console.log('Data fetched, groups:', groupStore.getAllGroups, 'tasks:', taskStore.getAllTasks)
    
    // 设置默认分组
    const allGroups = groupStore.getAllGroups;
    if (allGroups.length > 0) {
      if (!currentGroupId.value) {
        const firstGroup = allGroups[0];
        if (firstGroup) {
          currentGroupId.value = firstGroup.group_id;
          taskFormValue.value.group_id = currentGroupId.value;
          taskStore.setFilter({ groupId: currentGroupId.value });
          // 重新获取任务数据
          await taskStore.fetchTasks();
        }
      }
    }
  } catch (error) {
    console.error('初始化数据失败:', error);
    message.error('初始化数据失败');
  }
})
</script>

<style scoped>
.task-list-container {
  height: 100vh;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.sidebar-header h2 {
  margin: 0;
}

.group-actions {
  padding: 16px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.content {
  padding: 16px;
}

.filter-bar {
  margin-bottom: 16px;
}

.task-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.task-completed {
  text-decoration: line-through;
  color: #999;
}

.task-description {
  margin-top: 4px;
  color: #666;
}

.task-meta {
  display: flex;
  gap: 16px;
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}
</style>